/** 
 * All global uses of highcharts is fair game as we multiple charts in one window
 * will invalidate "one menu" approach anyway
 */

if ( typeof require != "undefined") {
  const electron = require('electron');
  const remote = require("remote");
  const Menu = remote.require('menu');
  const MenuItem = remote.require('menu-item');
  const currentWindow = remote.getCurrentWindow();
  const desktopjs = remote.require("./desktop-main.js");

  electron.ipcRenderer.on('reload', function (event, config) {
    //console.log("Received reload config: " + config);
    //processConfig(config);
  });

  var globalLogger = remote.getGlobal("logger");

  function WrappedLogger(logger) {
    this.log = function () {
      this.info(arguments);
    }
    this.info = function () {
      console.info.apply(console, arguments);
      logger.info.apply(this, arguments);
    }
    this.debug = function () {
      console.debug.apply(console, arguments);
      logger.debug.apply(this, arguments);
    }
    this.warn = function () {
      console.warn.apply(console, arguments);
      logger.warn.apply(this, arguments);
    }
    this.error = function () {
      console.error.apply(console, arguments);
      logger.error.apply(this, arguments);
    }

  }


  if (isDefined(globalLogger)) {
    logger = new WrappedLogger(globalLogger);
    console.log("******************************************")
    console.log("LOGGER DEFINED THROUGH NODE ", logger);
    console.log("******************************************")
  }

  function doReload() {
    disconnect();
    desktopjs.reload();
  }

  function saveGraphConfig(name, config) {
    desktopjs.saveGraphConfig(name, config);
  }

  function setBounds(bounds) {
    desktopjs.setBounds(bounds);
  }

  function getGraphConfig(name) {
    return desktopjs.getGraphConfig(name);
  }

  function changeWindowPixelSize(width, height ) {
    currentWindow.setContentSize(width, height);
  }

  function changeWindowSize(horizontalWindows, verticalWindows) {
    var electronScreen = remote.screen;
    var currentCursor = electronScreen.getCursorScreenPoint();
    var currentDisplay = electronScreen.getDisplayNearestPoint(currentCursor);

    var currentSize = currentWindow.getSize();
    var currentContent = currentWindow.getContentSize();
    var titleBarSize = currentSize[1] - currentContent[1];

    var displayWidth = currentDisplay.workAreaSize.width;
    var displayHeight = currentDisplay.workAreaSize.height - verticalWindows * titleBarSize;

    var width = displayWidth / horizontalWindows / 2;
    var height = displayHeight / verticalWindows / 2;
    width = parseInt(width, 10);
    height = parseInt(height, 10);

    console.log("width: ", width, "height:", height);
    currentWindow.setContentSize(width, height);
  }

  function changeWindowSizePrimary(horizontalWindows, verticalWindows) {
    var electronScreen = remote.screen;
    var currentDisplay = electronScreen.getPrimaryDisplay();

    var currentSize = currentWindow.getSize();
    var currentContent = currentWindow.getContentSize();
    var titleBarSize = currentSize[1] - currentContent[1];

    var displayWidth = currentDisplay.workAreaSize.width;
    var displayHeight = currentDisplay.workAreaSize.height - verticalWindows * titleBarSize;

    var width = displayWidth / horizontalWindows;
    var height = displayHeight / verticalWindows;
    width = parseInt(width, 10);
    height = parseInt(height, 10);


    console.log("width: ", width, "height:", height);
    currentWindow.setContentSize(width, height);
  }
  
  function internationalizeAndScrub( template ) {
    if ( !template ) return;
    template.forEach( function( item ) {
      internationalizeAndScrubItem( item );
    });
  }

  function internationalizeAndScrubItem( item ) {

    if ( item.submenu ) {
      item.submenu.forEach( function( subItem ) {
        internationalizeAndScrubItem( subItem );
      });
    }
  }

  function generateMenu( chart, x, y ) {
    var electronScreen = remote.screen;
    var currentDisplay = electronScreen.getPrimaryDisplay();
    var currentSize = currentWindow.getSize();
    var currentContent = currentWindow.getContentSize();
    var titleBarSize = currentSize[1] - currentContent[1];    
    var displayWidth = currentDisplay.workAreaSize.width;
    var displayHeight = currentDisplay.workAreaSize.height;

    var electronMenu = this;
    var menuConfig = {
      "mousePosition" : {
        "x" : x,
        "y" : y
      },
      "callbacks" : {
        "changeWindowSize" : electronMenu.changeWindowSize,
        "changeWindowPixelSize" : electronMenu.changeWindowPixelSize,
        "reload" : doReload
      }, 
      "screen" : {
        "titleBarSize" : titleBarSize,
        "primary" : {
          "width" : displayWidth,
          "height" : displayHeight
        }
      }
    };
    var template = chart.getContextMenu( menuConfig );
    internationalizeAndScrub( template );

    var menu = Menu.buildFromTemplate(template);
    menu.chart = chart;
    return menu;
  }

  window.addEventListener('contextmenu', function (e) {
    e.preventDefault();
    if (!highCharts) return;

    var menu = generateMenu( highCharts, e.x, e.y );

    menu.popup(remote.getCurrentWindow());
  }, false);

  $(document).keydown(function (e) {
    //turn on debug
    if (e.ctrlKey && e.shiftKey && e.which == 68) {
      e.preventDefault();
      console.log("toggling developer tools")
      currentWindow.toggleDevTools();
    }
    if (e.ctrlKey) {
      if (e.which >= 49 && e.which - 49 <= 8) {
        var windowsPerScreen = e.which - 48;
        console.log("Setting window size to: ", windowsPerScreen, ":", windowsPerScreen);
        changeWindowSize(windowsPerScreen, windowsPerScreen);
      }
    }
  });
} //if require is available (node)

